<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>畅所欲言-在线聊天室</title>
    <style>
        body {
            font-family: "Helvetica Neue",Helvetica,Arial,Verdana,Geneva,sans-serif,"宋体","微软雅黑";
            color: #333;
            font-size: 14px;
            max-width: 1180px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, rgba(238, 148, 245, 0.9), rgba(173, 216, 230, 0.8), rgba(135, 206, 235, 0.7));
            background-attachment: fixed;
            background-size: 100% 100%;
            min-height: 100vh;
        }
        .container {
            display: flex;
            flex-direction: row;
            gap: 20px;
            margin-bottom: 20px;
            height: calc(100vh - 120px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            border-radius: 8px;
            overflow: hidden;
            background-image: url('img/bg_alpha2.png');
            background-repeat: repeat;
            background-size: 150px 150px;
            background-opacity: 0.3;
        }
        .chat-section {
    width: 70%;
    background: linear-gradient(135deg, rgba(237, 168, 237, 0.25), rgba(192, 213, 244, 0.2), rgba(223, 205, 250, 0.22));
    backdrop-filter: blur(25px);
    border: 1px solid rgba(254, 165, 254, 0.65);
    border-radius: 20px;
    padding: 15px;
    box-shadow: 0 15px 50px rgba(140, 100, 255, 0.15), inset 0 0 15px rgba(255,255,255,0.3);
    background-clip: padding-box;
    display: flex;
    flex-direction: column;
    height: 100%;

}
        .users-section {
    width: 30%;
    background: linear-gradient(135deg, rgba(255,230,255,0.25), rgba(230,240,255,0.2), rgba(240,230,255,0.22));
    backdrop-filter: blur(25px);
    border: 1px solid rgba(253, 177, 253, 0.65);
    border-radius: 20px;
    padding: 15px;
    box-shadow: 0 15px 50px rgba(140, 100, 255, 0.15), inset 0 0 15px rgba(255,255,255,0.3);
    background-clip: padding-box;
    display: flex;
    flex-direction: column;
    height: 100%;

}
        h1 {
            text-align: center;
            margin: 25px 0 15px;
            font: 24px/34px "Microsoft Yahei";
            background: linear-gradient(135deg, #3480e2, #5d9de5);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h2 {
            color: #555;
            margin-top: 0;
            font-size: 18px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .controls {
            margin-bottom: 20px;
        }
        input, button {
            padding: 10px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        input[type="text"] {
            width: 60%;
            padding: 8px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            font-size: 14px;
        }
        input[type="text"]:focus {
            border-color: #5d9de5;
            outline: none;
            box-shadow: 0 0 0 2px rgba(93, 157, 229, 0.2);
        }
        button {
            background-color: #2a75d6;
            color: white;
            border: none;
            cursor: pointer;
            transition: all 0.3s ease;
            padding: 8px 15px;
            border-radius: 4px;
            font-size: 14px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        button:hover {
            background-color: #004699;
            box-shadow: 0 3px 8px rgba(0,0,0,0.15);
            transform: translateY(-1px);
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        #messageArea {
            flex: 1;
            border: 1px solid rgba(224, 224, 224, 0.5);
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            overflow-y: auto;
            background: linear-gradient(to bottom, rgba(255,255,255,0.7), rgba(245,250,255,0.7));
            backdrop-filter: blur(5px);
            font-family: "Helvetica Neue",Helvetica,Arial,Verdana,sans-serif;
            font-size: 14px;
            box-shadow: inset 0 1px 3px rgba(0,0,0,0.05);
            z-index: 1;
        }
        .system-message {
            color: #888;
            font-style: italic;
            padding: 5px 0;
            border-left: 2px solid #eee;
            padding-left: 10px;
            margin: 8px 0;
        }
        .user-message {
            text-align: right;
            margin: 8px 0;
            padding: 10px 15px;
            border-radius: 18px 18px 0 18px;
            background: linear-gradient(135deg, #3480e2, #5d9de5);
            color: white;
            display: inline-block;
            max-width: 70%;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            float: right;
            clear: both;
        }
        .received-message {
            text-align: left;
            margin: 8px 0;
            padding: 10px 15px;
            border-radius: 18px 18px 18px 0;
            background: linear-gradient(135deg, #f0f7ff, #e0ecff);
            color: #333;
            display: inline-block;
            max-width: 70%;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            float: left;
            clear: both;
        }
        .online-user {
            padding: 8px 12px;
            margin: 5px 0;
            background-color: rgba(230, 240, 255, 0.7);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
            border-left: 3px solid #3480e2;
            backdrop-filter: blur(5px);
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        .online-user:hover {
            background-color: #e0ecff;
            transform: translateX(3px);
        }
        .online-user.selected {
            background-color: #e0ecff;
            border-left: 3px solid #3480e2;
            font-weight: bold;
        }
        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #3480e2;
            margin-right: 8px;
            box-shadow: 0 0 0 rgba(52, 128, 226, 0.7);
            animation: pulse 2s infinite;
        }
        .connection-status {
            margin-left: 10px;
            padding: 4px 12px;
            border-radius: 16px;
            font-weight: bold;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        .status-connected {
            background: linear-gradient(135deg, #4cd964, #5ac8fa);
            color: white;
            box-shadow: 0 3px 10px rgba(76, 217, 100, 0.3), 0 0 0 1px rgba(76, 217, 100, 0.2);
            animation: pulse 2s infinite;
        }
        .status-disconnected {
            background: linear-gradient(135deg, #ff6b6b, #ff9e80);
            color: white;
            box-shadow: 0 3px 10px rgba(255, 107, 107, 0.3), 0 0 0 1px rgba(255, 107, 107, 0.2);
        }
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(52, 128, 226, 0.7); }
            70% { box-shadow: 0 0 0 6px rgba(52, 128, 226, 0); }
            100% { box-shadow: 0 0 0 0 rgba(52, 128, 226, 0); }
        }
        .user-count {
            font-size: 12px;
            color: #666;
            margin-bottom: 10px;
        }
        .broadcast-checkbox {
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <!--#include virtual="header.html" -->
<h1>畅所欲言-在线聊天室</h1>

<div class="container">
    <div class="chat-section">
        <div class="controls">
            <label for="userIdInput">用户ID: </label>
            <input type="text" id="userIdInput" placeholder="请输入您的用户ID" value="username">
            <button id="connectBtn">连接</button>
            <button id="disconnectBtn" disabled>断开连接</button>
            <span id="connectionStatus" class="connection-status status-disconnected">未连接</span>
        </div>

        <div id="messageArea">
            <div class="system-message">系统: 欢迎来到畅所欲言-在线聊天室!请输入用户ID并点击连接按钮开始聊天。</div>
        </div>

        <div class="controls">
            <label for="messageInput">消息内容: </label>
            <input type="text" id="messageInput" placeholder="请输入消息内容" disabled>
            <button id="sendBtn" disabled>发送消息</button>
            <label class="broadcast-checkbox">
                <input type="checkbox" id="broadcastCheckbox"> 广播消息
            </label>
        </div>
    </div>

    <div class="users-section">
        <h2>在线用户列表</h2>
        <div class="user-count">当前在线: <span id="onlineCount">0</span> 人</div>
        <div id="onlineUsersList">
            <!-- 在线用户将在这里动态显示 -->
        </div>
    </div>
</div>

<script>
    // WebSocket相关变量
    let ws = null;
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    const reconnectDelay = 3000;
    let selectedUserId = null;
    let heartbeatInterval = null;
    const heartbeatIntervalMs = 30000; // 30秒心跳

    // DOM元素
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const connectionStatus = document.getElementById('connectionStatus');
    const messageArea = document.getElementById('messageArea');
    const messageInput = document.getElementById('messageInput');
    const sendBtn = document.getElementById('sendBtn');
    const userIdInput = document.getElementById('userIdInput');
    const broadcastCheckbox = document.getElementById('broadcastCheckbox');
    const onlineUsersList = document.getElementById('onlineUsersList');
    const onlineCount = document.getElementById('onlineCount');

    // 从URL获取用户ID参数并自动连接
    document.addEventListener('DOMContentLoaded', function() {
        const urlParams = new URLSearchParams(window.location.search);
        const userId = urlParams.get('userId');
        if (userId) {
            // 隐藏用户ID输入框和连接按钮
            userIdInput.style.display = 'none';
            connectBtn.style.display = 'none';
            disconnectBtn.style.display = 'none';
            document.querySelector('.controls').style.marginBottom = '5px';

            userIdInput.value = userId;
            connectWebSocket();
        }
    });

    // 初始化事件监听
    connectBtn.addEventListener('click', connectWebSocket);
    disconnectBtn.addEventListener('click', disconnectWebSocket);
    sendBtn.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', function(event) {
        if (event.key === 'Enter') {
            sendMessage();
        }
    });
    broadcastCheckbox.addEventListener('change', updateSendButtonText);

    // 更新发送按钮文本
    function updateSendButtonText() {
        sendBtn.textContent = broadcastCheckbox.checked ? '广播消息' : '发送消息';
    }

    // 连接WebSocket
    function connectWebSocket() {
        const userId = userIdInput.value.trim();
        if (!userId) {
            showMessage('系统', '请输入用户ID', 'system');
            return;
        }

        // WebSocket URL - 使用正确的端点路径
        const wsUrl = `ws://localhost:8081/websocket/ws?userId=${encodeURIComponent(userId)}`;

        try {
            ws = new WebSocket(wsUrl);

            ws.onopen = function() {
                showMessage('系统', '连接成功', 'system');
                connectionStatus.textContent = '已连接';
            connectionStatus.classList.remove('status-disconnected');
            connectionStatus.classList.add('status-connected');
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                messageInput.disabled = false;
                sendBtn.disabled = false;
                reconnectAttempts = 0;

                // 启动心跳
                startHeartbeat();
            };

            ws.onmessage = function(event) {
                const message = event.data;
                try {
                    // 尝试解析JSON消息
                    const parsedMessage = JSON.parse(message);

                    // 处理用户列表更新消息
                    if (parsedMessage.type === 'USER_LIST_UPDATE') {
                        updateOnlineUsersList(parsedMessage.users);
                        showMessage('系统', `在线用户列表已更新，当前在线${parsedMessage.users.length}人`, 'system');
                    }
                    // 处理用户消息
                    else if (parsedMessage.type === 'USER_MESSAGE') {
                        showMessage(parsedMessage.from, parsedMessage.content, 'received');
                    }
                    // 处理系统消息
                    else if (parsedMessage.type === 'SYSTEM_MESSAGE') {
                        showMessage('系统', parsedMessage.content, 'system');
                    }
                    // 处理心跳响应
                    else if (parsedMessage.type === 'HEARTBEAT_RESPONSE') {
                        // 心跳响应，无需显示
                    }
                    // 普通文本消息
                    else {
                        showMessage('服务器', message, 'received');
                    }
                } catch (e) {
                    // 如果不是JSON格式，按普通消息处理
                    showMessage('服务器', message, 'received');
                }
            };

            ws.onclose = function(event) {
                showMessage('系统', `连接已关闭 (代码: ${event.code})`, 'system');
                connectionStatus.textContent = '未连接';
            connectionStatus.classList.remove('status-connected');
            connectionStatus.classList.add('status-disconnected');
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                messageInput.disabled = true;
                sendBtn.disabled = true;

                // 停止心跳
                stopHeartbeat();

                // 清空在线用户列表
                clearOnlineUsersList();

                // 如果不是主动断开连接，尝试重连
                if (event.code !== 1000 && reconnectAttempts < maxReconnectAttempts) {
                    reconnectAttempts++;
                    showMessage('系统', `将在 ${reconnectDelay/1000} 秒后尝试重新连接...`, 'system');
                    setTimeout(connectWebSocket, reconnectDelay);
                } else if (reconnectAttempts >= maxReconnectAttempts) {
                    showMessage('系统', '已达到最大重连次数，请检查服务器状态后手动重连', 'system');
                }
            };

            ws.onerror = function(error) {
                showMessage('系统', '连接错误，请检查服务器地址是否正确', 'system');
            };

        } catch (e) {
            showMessage('系统', 'WebSocket初始化失败: ' + e.message, 'system');
        }
    }

    // 断开WebSocket连接
    function disconnectWebSocket() {
        if (ws) {
            ws.close();
            ws = null;
        }
    }

    // 发送消息
    function sendMessage() {
        const message = messageInput.value.trim();
        const userId = userIdInput.value.trim();

        if (!message) {
            showMessage('系统', '消息内容不能为空', 'system');
            return;
        }

        if (!ws || ws.readyState !== WebSocket.OPEN) {
            showMessage('系统', '连接未建立，请先连接服务器', 'system');
            return;
        }

        try {
            if (broadcastCheckbox.checked) {
                // 发送广播消息
                const broadcastMsg = JSON.stringify({
                    type: 'BROADCAST_MESSAGE',
                    content: message,
                    from: userId
                });
                ws.send(broadcastMsg);
                showMessage('我(广播)', message, 'user');
            } else if (selectedUserId) {
                // 发送给特定用户
                const directMsg = JSON.stringify({
                    type: 'DIRECT_MESSAGE',
                    to: selectedUserId,
                    content: message,
                    from: userId
                });
                ws.send(directMsg);
                showMessage(`我 -> ${selectedUserId}`, message, 'user');
            } else {
                showMessage('系统', '请先选择要发送消息的用户', 'system');
                return;
            }

            messageInput.value = '';
        } catch (e) {
            showMessage('系统', '发送消息失败: ' + e.message, 'system');
        }
    }

    // 显示消息
    function showMessage(sender, content, type) {
        const messageDiv = document.createElement('div');
        messageDiv.className = type + '-message';

        if (type === 'system') {
            messageDiv.textContent = content;
        } else {
            messageDiv.textContent = `${sender}: ${content}`;
        }

        messageArea.appendChild(messageDiv);
        messageArea.scrollTop = messageArea.scrollHeight;
    }

    // 更新在线用户列表
    function updateOnlineUsersList(users) {
        // 获取当前用户ID
        const currentUserId = userIdInput.value.trim();

        // 清空现有列表
        onlineUsersList.innerHTML = '';

        // 添加每个在线用户（排除自己）
        users.forEach(userId => {
            // 只添加其他用户，不显示自己
            if (userId !== currentUserId) {
                const userDiv = document.createElement('div');
                userDiv.className = 'online-user' + (selectedUserId === userId ? ' selected' : '');
                userDiv.innerHTML = `<span class="status-indicator"></span>${userId}`;
                userDiv.onclick = function() {
                    selectUser(userId);
                };
                onlineUsersList.appendChild(userDiv);
            }
        });

        // 更新在线用户数量（包括自己）
        onlineCount.textContent = users.length;
    }

    // 选择用户
    function selectUser(userId) {
        selectedUserId = userId;

        // 更新UI显示选中状态
        const userElements = document.querySelectorAll('.online-user');
        userElements.forEach(el => {
            if (el.textContent.includes(userId)) {
                el.classList.add('selected');
            } else {
                el.classList.remove('selected');
            }
        });

        // 自动取消广播选项
        broadcastCheckbox.checked = false;
        updateSendButtonText();
    }

    // 清空在线用户列表
    function clearOnlineUsersList() {
        onlineUsersList.innerHTML = '';
        onlineCount.textContent = '0';
        selectedUserId = null;
    }

    // 启动心跳
    function startHeartbeat() {
        stopHeartbeat(); // 先停止可能存在的心跳
        heartbeatInterval = setInterval(() => {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({ type: 'HEARTBEAT' }));
            }
        }, heartbeatIntervalMs);
    }

    // 停止心跳
    function stopHeartbeat() {
        if (heartbeatInterval) {
            clearInterval(heartbeatInterval);
            heartbeatInterval = null;
        }
    }

    // 页面关闭时清理
    window.addEventListener('beforeunload', function() {
        stopHeartbeat();
        if (ws) {
            ws.close();
        }
    });
</script>
    <!--#include virtual="footer.html" -->
</body>
</html>
